<script setup lang="ts">
import type { CreateTenantRequest, TenantItem, UpdateTenantRequest } from '#/api/tenant';

import { computed, onMounted, reactive, ref } from 'vue';

import { Button, Col, DatePicker, Form, Input, InputNumber, Row, Switch } from 'ant-design-vue';
import dayjs from 'dayjs';

import { tenantApi } from '#/api/tenant';

interface Props {
  mode: 'create' | 'edit';
  data?: TenantItem;
}

interface Emits {
  (e: 'success'): void;
  (e: 'cancel'): void;
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'create',
});

const emit = defineEmits<Emits>();

defineOptions({
  name: 'TenantForm',
});

// 表单引用
const formRef = ref();
const loading = ref(false);

// 表单数据
const formData = reactive({
  name: '',
  code: '',
  domain: '',
  is_active: true,
  max_users: 100,
  expire_at: undefined as any,
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入租户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '租户名称长度为2-50个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入租户编码', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9_-]+$/, 
      message: '租户编码只能包含字母、数字、下划线和横线', 
      trigger: 'blur' 
    },
    { min: 2, max: 20, message: '租户编码长度为2-20个字符', trigger: 'blur' },
  ],
  domain: [
    { 
      pattern: /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, 
      message: '请输入有效的域名格式', 
      trigger: 'blur' 
    },
  ],
  max_users: [
    { required: true, message: '请输入最大用户数', trigger: 'blur' },
    { type: 'number', min: 1, max: 10000, message: '最大用户数范围为1-10000', trigger: 'blur' },
  ],
};

// 计算属性
const title = computed(() => props.mode === 'create' ? '新增租户' : '编辑租户');
const submitText = computed(() => props.mode === 'create' ? '创建' : '更新');

// 初始化表单数据
const initFormData = () => {
  if (props.mode === 'edit' && props.data) {
    Object.assign(formData, {
      name: props.data.name,
      code: props.data.code,
      domain: props.data.domain,
      is_active: props.data.is_active,
      max_users: props.data.max_users,
      expire_at: props.data.expire_at ? dayjs(props.data.expire_at) : undefined,
    });
  } else {
    // 重置为默认值
    Object.assign(formData, {
      name: '',
      code: '',
      domain: '',
      is_active: true,
      max_users: 100,
      expire_at: undefined,
    });
  }
};

// 表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    const submitData = {
      ...formData,
      expire_at: formData.expire_at ? formData.expire_at.toISOString() : undefined,
    };

    if (props.mode === 'create') {
      await tenantApi.create(submitData as CreateTenantRequest);
    } else {
      await tenantApi.update({
        ...submitData,
        id: props.data!.id,
      } as UpdateTenantRequest);
    }

    emit('success');
  } catch (error) {
    console.error('表单提交失败:', error);
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  emit('cancel');
};

// 重置表单
const handleReset = () => {
  formRef.value.resetFields();
  initFormData();
};

// 组件挂载时初始化数据
onMounted(() => {
  initFormData();
});
</script>

<template>
  <div class="tenant-form">
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      :label-col="{ span: 24 }"
      :wrapper-col="{ span: 24 }"
    >
      <Row :gutter="16">
        <Col :span="12">
          <Form.Item label="租户名称" name="name">
            <Input
              v-model:value="formData.name"
              placeholder="请输入租户名称"
              :maxlength="50"
              show-count
            />
          </Form.Item>
        </Col>
        <Col :span="12">
          <Form.Item label="租户编码" name="code">
            <Input
              v-model:value="formData.code"
              placeholder="请输入租户编码"
              :maxlength="20"
              :disabled="mode === 'edit'"
              show-count
            />
          </Form.Item>
        </Col>
      </Row>

      <Row :gutter="16">
        <Col :span="12">
          <Form.Item label="域名" name="domain">
            <Input
              v-model:value="formData.domain"
              placeholder="请输入域名（可选）"
              :maxlength="100"
            />
          </Form.Item>
        </Col>
        <Col :span="12">
          <Form.Item label="最大用户数" name="max_users">
            <InputNumber
              v-model:value="formData.max_users"
              placeholder="请输入最大用户数"
              :min="1"
              :max="10000"
              style="width: 100%"
            />
          </Form.Item>
        </Col>
      </Row>

      <Row :gutter="16">
        <Col :span="12">
          <Form.Item label="过期时间" name="expire_at">
            <DatePicker
              v-model:value="formData.expire_at"
              placeholder="请选择过期时间（可选）"
              style="width: 100%"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>
        </Col>
        <Col :span="12">
          <Form.Item label="状态" name="is_active">
            <Switch
              v-model:checked="formData.is_active"
              checked-children="启用"
              un-checked-children="禁用"
            />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item>
        <div class="flex justify-end gap-2">
          <Button @click="handleCancel">
            取消
          </Button>
          <Button @click="handleReset">
            重置
          </Button>
          <Button 
            type="primary" 
            :loading="loading"
            @click="handleSubmit"
          >
            {{ submitText }}
          </Button>
        </div>
      </Form.Item>
    </Form>
  </div>
</template>

<style scoped>
.tenant-form {
  padding: 24px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}

:deep(.ant-input-number) {
  width: 100%;
}
</style>